﻿using Accord.Statistics.Testing;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KsTest2
{
    class Program
    {

        private static DataTable GetDataTable(SqlCommand cmd)
        {
            if (cmd.Connection.State == ConnectionState.Closed || cmd.Connection.State == ConnectionState.Broken)
                cmd.Connection.Open();


            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            return dt;

        }

        private static  DataSet GetDataSet(SqlCommand cmd)
        {
            if (cmd.Connection.State == ConnectionState.Closed || cmd.Connection.State == ConnectionState.Broken)
                cmd.Connection.Open();
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            adapter.SelectCommand = cmd;
            adapter.Fill(ds);
            return ds;
        }

        static void Main(string[] args)
        {
            string path = System.Reflection.Assembly.GetEntryAssembly().CodeBase;

            string dir = Path.GetDirectoryName(path);

            Uri u = new Uri(dir);

            Directory.SetCurrentDirectory(u.LocalPath);

            string connectionString = File.ReadAllText("ConnectionString.txt");

            string outputFile = DateTime.Now.ToLongTimeString().Replace(":","_") + "_log.txt";

            FileStream fStream = new FileStream(outputFile, FileMode.Create);

            StreamWriter writer = new StreamWriter(fStream);

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                SqlCommand pendingCmd = new SqlCommand("usp_GetPendingKsTests", conn);
                pendingCmd.CommandType = CommandType.StoredProcedure;

                DataTable pending = GetDataTable(pendingCmd);

                foreach (DataRow r in pending.Rows)
                {

                    int id = int.Parse(r["id"].ToString());
                    int dataRun1 = int.Parse(r["DataRun1"].ToString());
                    int dataRun2 = int.Parse(r["DataRun2"].ToString());

                    SqlCommand startedCmd = new SqlCommand("usp_StartKsTest", conn);
                    startedCmd.CommandType = CommandType.StoredProcedure;
                    startedCmd.Parameters.Add(new SqlParameter("id", id));
                    startedCmd.ExecuteNonQuery();

                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.CommandText = "usp_GetDataForKsTest";

                     cmd.Parameters.Add(new SqlParameter("DataRun1", dataRun1));
                     cmd.Parameters.Add(new SqlParameter("DataRun2", dataRun2));

         

                    DataSet ds = GetDataSet(cmd);

                    List<List<double>> data = new List<List<double>>(2);

                    //there will be exactly two tables in result set when passed two valid DataRun ids.
                    foreach (DataTable t in ds.Tables)
                    {
                        List<double> set = new List<double>(t.Rows.Count);
                        data.Add(set);
                        foreach (DataRow r2 in t.Rows)
                        {
                            double d = double.Parse(r2["d"].ToString());
                            set.Add(d);
                        }
                    }

                    writer.WriteLine("Processing request id " + id );

                    double[] setArray1 = data[0].ToArray();
                    double[] setArray2 = data[1].ToArray();


                    writer.Write("SetArray1" + Environment.NewLine + string.Join(Environment.NewLine, setArray1));
                    writer.Write(Environment.NewLine + "SetArray2" + Environment.NewLine + string.Join(Environment.NewLine, setArray2));

                    var ks = new TwoSampleKolmogorovSmirnovTest(setArray1, setArray2);

                    writer.WriteLine(Environment.NewLine + "KS results: " + ks.PValue + "\t" + ks.Significant);


                    SqlCommand resultCommand = new SqlCommand("usp_CompletedKsTest", conn);
                    resultCommand.CommandType = CommandType.StoredProcedure;
                    resultCommand.Parameters.Add(new SqlParameter("id", id));
                    resultCommand.Parameters.Add(new SqlParameter("PValue", ks.PValue));
                    resultCommand.Parameters.Add(new SqlParameter("Significant", ks.Significant));
                    resultCommand.ExecuteNonQuery();
                }


            }
            writer.Flush();
            fStream.Flush();
            writer.Close();
            fStream.Close();
        }
    }
}
